<template>
  <uv-form labelPosition="left" :model="model" :rules="rules" ref="form">
    <view v-for="([key, field]) in Object.entries(options)" :key="key" class="borderbottom">
      <uv-form-item :label="field.title" :prop="'userInfo.' + key" label-width="120" labelPosition="left" labelAlign="center">
        <component :is="getFieldComponent(field)" :field="field" v-model="model[key]" :readonly="readonly" />
      </uv-form-item>
      
      <!-- 子选项渲染 -->
      <view v-if="field.rateInfo || key == 'rateInfo'">
        <payRateVue ref="payRate" :disabled="readonly" :options="field.rateInfo ?? field" :payRateInfo="model.rateInfo || {}"></payRateVue>
      </view>
      
      <view v-if="field.subTitle" class="subTitle">{{ field.subTitle }}</view>
      
      <template v-if="field.type === 'timeRadio'">
        <dataTimepicker :timeType="model[key]"></dataTimepicker>
      </template>
    </view>
  </uv-form>
</template>

<script>
import inputField from '@/components/form/inputField/inputField.vue';
import uploadField from '@/components/form/uploadField/uploadField.vue';
import radioField from '@/components/form/radioField/radioField.vue';
import checkboxField from '@/components/form/checkboxField/checkboxField.vue';
import poupCheckbox from '@/components/form/poupCheckbox/poupCheckbox.vue';
import shopUserPick from '@/pages/tabbar/work/pages/addShopUser/current/shopUserPick.vue';
import dataTimepicker from '@/components/dataTimepicker/dataTimepicker.vue';
import areaVue from '@/components/form/area/area.vue';
import mapVue from '@/components/form/map/map.vue';
import scollPickVue from '@/components/scollPick/scollPick.vue';
import payRateVue from '@/components/FormComponent/payRate.vue';

export default {
  components: {
    inputField,
    uploadField,
    radioField,
    checkboxField,
    payRateVue,
    poupCheckbox,
    shopUserPick,
    dataTimepicker,
    areaVue,
    mapVue,
    scollPickVue,
  },
  props: {
    options: {
      type: Object,
      required: true,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    formInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      model: {},
      rules: {},
      timeRadioItems: [
        { name: '选择时间', value: '0', checked: false },
        { name: '长期有效', value: '1', checked: false },
      ],
      modelInitialized: false,
    };
  },
  computed: {
    fields() {
      return this.options;
    },
  },
  mounted() {
    this.rules = this.generateRules();
    if (!this.formInfo && !this.modelInitialized) {
      this.initForm();
      this.modelInitialized = true;
    } else {
      this.model = this.formInfo;
    }

    uni.$on('selectIndustry', this.handleSelectIndustry);
    uni.$on('bankBranch', this.handleBankBranch);
  },
  beforeDestroy() {
    uni.$off('selectIndustry', this.handleSelectIndustry);
    uni.$off('bankBranch', this.handleBankBranch);
  },
  methods: {
    getFieldComponent(field) {
      switch (field.type) {
        case 'input':
          return 'InputField';
        case 'upload':
          return 'UploadField';
        case 'radio':
          return 'RadioField';
        case 'checkbox':
          return 'CheckboxField';
        case 'poupCheckbox':
          return 'poupCheckbox';
        case 'poupShopCheckbox':
          return 'shopUserPick';
        case 'area':
          return 'areaVue';
        case 'map':
          return 'mapVue';
        case 'scollPicker':
          return 'scollPickVue';
        case 'timeRadio':
          return 'dataTimepicker';
        default:
          return 'div';
      }
    },
    handleSelectIndustry(e) {
      this.model['companyCategory'] = e;
    },
    handleBankBranch(e) {
      this.model['bankBranch'] = e;
    },
    initForm() {
      Object.entries(this.options).forEach(([key, field]) => {
        if (field.type === 'radio' || field.type === 'timeRadio') {
          this.model[key] = '0';
        } else if (field.type === 'checkbox') {
          this.model[key] = [];
        } else {
          this.model[key] = field.value || '';
        }
      });
    },
    getModel() {
      let model = this.model;
      if (this.$refs.payRate) {
        this.model['rateInfo'] = this.$refs.payRate[0].model;
      }
      return model;
    },
    validate() {
      this.$refs.form.validate().then(() => {
        uni.showToast({
          icon: 'success',
          title: '校验通过',
        });
      }).catch(() => {
        uni.showToast({
          icon: 'error',
          title: '校验失败',
        });
      });
    },
    generateRules() {
      return Object.fromEntries(Object.entries(this.fields).map(([key, field]) => {
        return field.validate ? [
          `userInfo.${key}`,
          {
            required: field.validate.required,
            message: `${field.title} 是必填项`,
            trigger: ['blur', 'change'],
          },
        ] : null;
      }).filter(Boolean));
    },
  },
};
</script>

<style scoped lang="scss">
.mar10 {
  margin: 10rpx;
}

.subTitle {
  font-size: 24rpx;
  color: var(--themeDefultFontColor);
  margin: 10rpx 0;
}
</style>
